package myJs.user.soft

import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg.LayerOptions
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Event, _}
import scalatags.Text.all._

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("LongData2Fat")
object LongData2Fat {
  val formId = "form"
  val kind = "long2fat"

  @JSExport("init")
  def init = {
    bootStrapValidator
    $("#form").bv.revalidateField("missionName")

    $("a[data-toggle='tab']").on("show.bs.tab", (y: Element, e: Event) => {
      val tabId = $(y).attr("href").get
      tabId match {
        case "#csvFile" => tabValidator("csvFile")
        case "#txtFile" => tabValidator("txtFile")
        case "#xlsxFile" => tabValidator("xlsxFile")
        case "#hand" => tabValidator("fileContent")
      }
    })
  }

  def tabValidator(enField: String) = {
    List("xlsxFile", "fileContent", "txtFile", "csvFile").foreach { fieldName =>
      val bv = $(s"#${formId}").bv
      if (enField != fieldName) {
        bv.enableFieldValidators(fieldName, false)
      } else {
        bv.enableFieldValidators(fieldName, true)
      }
    }
  }

  @JSExport("showExample")
  def showExample(y: Element, name: String) = {
    val url = g.jsRoutes.controllers.SoftController.getFileContent().url.toString
    Ajax.get(url = s"${url.noCache}&kind=${kind}&fileName=example.txt", headers = Map("Content-Type" -> "application/json")).
      map { xhr =>
        val rs = xhr.responseText
        $(s"textarea[name='${name}']").`val`(rs)
        $(s"#${formId}").bv.revalidateField(name)
      }
  }

  @JSExport("myRun")
  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      val inputKind = $("#inputKind li.active").text().trim
      formData.append("inputKind", inputKind)
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.SoftController.long2fat().url.toString
      val xhr = new XMLHttpRequest
      xhr.open("post", url)
      xhr.upload.onprogress = progressHandlingFunction
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val data = xhr.response
          val rs = JSON.parse(data.toString).toJDJAn
          layer.close(index)
          val valid = rs("valid").toB
          if (valid) {
            window.location.href = g.jsRoutes.controllers.MissionController.missionManageBefore().url.toString
          } else {
            g.swal("Error", rs.myGet("message"), "error")
          }
        }
      }
      xhr.send(formData)
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.MissionController.missionNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "missionName" ->{
          val info=messages("taskName")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("exist")}",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000,
                "data" -> js.Dictionary(
                  "missionName" -> $("input[name='missionName']").`val`(),
                  "kind" -> kind
                )
              ),
            )
          )
        },
        "csvFile" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "file" -> js.Dictionary(
                "message" -> messages("IncorrectFormat"),
                "extension" -> "csv",
              ),
            )
          )
        } ,
        "xlsxFile" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "file" -> js.Dictionary(
                "message" ->  messages("IncorrectFormat"),
                "extension" -> "xlsx",
              ),
            )
          )
        } ,
        "txtFile" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "file" -> js.Dictionary(
                "message" -> messages("IncorrectFormat"),
                "extension" -> "txt",
              ),
            )
          )
        } ,
        "fileContent" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
            )
          )
        },
      )
    )

    $(s"#form").bootstrapValidator(dict)
  }


}
